package leetcode.weekly.week310;

import java.util.Arrays;
import java.util.Map;
import java.util.TreeMap;

import leetcode.helper.H;

//Solution3Test
public class Solution5 {
	public int minGroups(int[][] intervals) {
		Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
		H.print(intervals);
		TreeMap<Integer, Integer> set = new TreeMap<>();
		for (int[] ints : intervals) {
			int start = ints[0], end = ints[1];
			Map.Entry<Integer, Integer> follow = set.floorEntry(start);
			if (follow == null) {
				set.put(end, 1);
			} else {
				int rest = follow.getValue() - 1;
				if (rest == 0) {
					set.remove(follow.getKey());
				}
				int add = set.getOrDefault(end, 0);
				set.put(end, add + 1);
			}
		}
		int ans = 0;
		for (Map.Entry<Integer, Integer> entry : set.entrySet()) {
			ans+=entry.getValue();
		}
		return ans;
	}

}
